package com.perfma.xtest.cmd;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * store trigger log in each log-file
 */
public class JobFileAppender {
    private static final Logger logger = LoggerFactory.getLogger(JobFileAppender.class);

    // for JobThread (support log for child thread of job handler)
    //public static ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    public static final InheritableThreadLocal<String> contextHolder = new InheritableThreadLocal<String>();
    public static final String logPath = GetLogPath();

    public static String GetLogPath() {
        String appPath = System.getProperty("app.path");
        File logFile = new File(appPath, "logs");
        if (!logFile.exists()) {
            logger.info("创建临时文件路径:{}", logFile.getAbsolutePath());
            logFile.mkdirs();
        }
        return logFile.getAbsolutePath();
    }

    /**
     * @param logId
     * @return
     */
    public static String makeLogFileName(Long logId) {

        // filePath/
        File filePathDir = new File(logPath + "/job");
        if (!filePathDir.exists()) {
            logger.info("创建日志文件路径:{}", filePathDir.getAbsolutePath());
            filePathDir.mkdirs();
        }

        return "/job/".concat(String.valueOf(logId)).concat(".log");
    }

    public static String makeTagLogFileName(long logId) {
        File filePathDir = new File(logPath + "/job");
        if (!filePathDir.exists()) {
            logger.info("创建日志文件路径:{}", filePathDir.getAbsolutePath());
            filePathDir.mkdirs();
        }

        return "/job/".concat("log4j-" + logId).concat(".log");
    }

    /**
     * append log
     *
     * @param logFileName
     * @param appendLog
     */
    public static void appendLog(String logFileName, String appendLog) {

        // log
        if (appendLog == null) {
            appendLog = "";
        }
        appendLog += "\r\n";

        // log file
        if (logFileName == null || logFileName.trim().length() == 0) {
            return;
        }
        File logFile = new File(logPath, logFileName);

        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                return;
            }
        }

        // append file content
        try {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(logFile, true);
                fos.write(appendLog.getBytes(StandardCharsets.UTF_8));
                fos.flush();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

    }

    /**
     * support read log-file
     *
     * @param logFileName
     * @return log content
     */
    public static LogResult readLog(String logFileName, int readSize) {
        File logFile = new File(logPath, logFileName);

        if (!logFile.exists()) {
            return new LogResult("读取日志失败,日志不存在\n", true);
        }
        StringBuffer sb = new StringBuffer();
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(logFile, "r")) {
            byte[] fileByte = null;
            long size = logFile.length();
            long sickSize = 0;
            if (size > readSize) {
                sickSize = size - readSize;
                randomAccessFile.seek(sickSize);
                fileByte = new byte[readSize];
            } else {
                fileByte = new byte[(int) size];
            }
            randomAccessFile.read(fileByte);
            sb.append(new String(fileByte, StandardCharsets.UTF_8));
        } catch (Exception e) {
            logger.error("文件读取出错,文件为:{}", logFile.getAbsolutePath());
        }
        LogResult logResult = new LogResult(sb.toString(), false);
        return logResult;
    }

    /**
     * read log data
     *
     * @param logFile
     * @return log line content
     */
    public static String readLines(File logFile) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(logFile), StandardCharsets.UTF_8));
            if (reader != null) {
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                return sb.toString();
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }

}
